import { marked } from "marked";
import $ from 'jquery'

function msg(obj) {
  const init = {
    text: '',
    title: '提示',
    delay: 2000,
    allowClick: false,
    zt: null
  }

  if (typeof obj == 'string' || typeof obj == 'number') {
    init.text = obj.toString()
  } else {
    for (let k in obj) {
      init[k] = obj[k]
    }
  }

  init.text = init.text.toString()

  let msg_wrap = $('.msg_wrap')

  if (!msg_wrap.length) {
    msg_wrap = $(`<div class="msg_wrap markdown-body" style="margin-left: 0.4rem;margin-bottom: 0.3rem;height: unset;padding: unset;background: unset;overflow: unset;box-shadow: unset;">`)
    $(document.body).append(msg_wrap)
  }


  const md = $(marked.parse(init.text))
  md.find('*').each((i, e) => {
    if (e.innerHTML == '') {
      e.remove()
    }
  })

  const is_first = msg_wrap.find('*').length == 0
  const msg_content = $(`<div class="msg_content">`)
  const title_elem = $(`<h4>${init.title}</h4>`)
  const msg_elem = $(`<p>${md.html()}</p>`)

  msg_content.append(title_elem)
  msg_content.append(msg_elem)
  msg_wrap.append(msg_content)

  const mc_w = msg_content.outerWidth()
  const mc_h = msg_content.outerHeight()

  let msg_w = ''
  {
    // 手动设置大小
    const clone_wrap = $(msg_wrap[0].cloneNode()).html('')
    const clone_contnet = $(msg_content[0].cloneNode(true))

    clone_wrap.append(clone_contnet)
    $(document.body).append(clone_wrap)

    msg_w = clone_contnet.outerWidth()
    clone_wrap.remove()
  }

  msg_content.css({
    marginLeft: -mc_w + 'px',
    marginBottom: is_first ? 0 : -mc_h + 'px',
    pointerEvents: init.allowClick ? 'auto' : 'none',
    width: msg_w / parseFloat(document.documentElement.style.fontSize) + 'rem'
  }).animate({
    marginLeft: '0.4rem',
    marginBottom: '0.3rem'
  }, () => msg_content.delay(init.delay).animate({
    marginLeft: -mc_w + 'px',
    opacity: 0
  }, () => msg_content.delay(500).remove()))

  return new Promise(resolve => setTimeout(() => resolve(), init.zt ?? init.delay))
}

export {msg}